import 'whatwg-fetch';


// get请求
const _get = ({ url, query}) => {
	let _url;
	if(query) {
		_url = `https://cnodejs.org/api/v1${url}?${query}`;
	}else{
		_url = `https://cnodejs.org/api/v1${url}`;
	}
	return fetch(_url)
		.then((res) => {
			if (res.status >= 200 && res.status < 300) {
				return res.json();
			}
			return Promise.reject(new Error(res.status));
		});
};

//POST 请求
const _post = (url,params) => {
	return fetch(`https://cnodejs.org/api/v1${url}`,{
		method: 'POST',
		headers: {
			Accept: 'application/json',
			'Content-Type': 'application/json',
		},
		body: JSON.stringfy(params),
	}).then((res)=> {
		if (res.status >=200 && res.status < 300){
			return res.json();
		}
		return Promise.reject(new Error(res.status));
	});
};

// 获取文章列表
export const fetchTopicList = ({commit},topicListObject) => {
	const topicTab = topicListObject.topicTab;
	const currentPage = topicListObject.currentPage;
	const url = '/topics';
	const query = `tab=${topicTab}&page=${currentPage}`;
	return _get({url,query})
		.then((json) => {
			if (json.success) {
				console.log(json.data);
				json.topicTab = topicTab;
				json.currentPage = currentPage;
				commit('FETCH_TOPIC_LISTS_SUCCESS',json);
			}else {
				Promise.reject(new Error('fetchTopicLists failure'));
			}
		})
};
//获取文章
export const fetchTopic = ({commit},id) => {
	const url = `/topic/${id}`;
	return _get({url})
		.then((json) => {
			if(json.success){
				console.log(json.data);
				commit('FETCH_TOPIC_SUCCESS',json.data);
				return json.data.author.loginname;
			}else{
				return Promise.rejet(new Error('fetchTopic failure'))
			}
		})
};
// 初始化提示
export const initHint = ({commit}) => commit('INIT_HINT');
// 显示提示
export const showHint = ({commit}) => commit('SHOW_HINT');